<?php

namespace App\Http\Controllers\webhook;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Symfony\Component\Process\Process;

class AuthController extends Controller
{
    //
    public function index()
    {
        $payload = file_get_contents('php://input');
        if (!empty($payload)) {
            $payload = json_decode($payload, true);

            // 验证请求的合法性
            $signature = request()->header('X-Gitee-Token');
            if ($signature != $this->webhooksAuth['password']) {
                // 验证失败
                echo "Invalid signature provided for webhook";
            }

            // 如果是push事件
            if ($payload['ref'] == 'refs/heads/dev') {
                // /www/wwwroot/wechat/kerrycake_admin/.git/objects目录授予777权限
                $process = new Process(['chmod -R 777 /www/wwwroot/wechat/kerrycake_admin/.git/objects']);
                $process->run();

                // 设置全局的用户名和邮箱
                $gitConfigProcess = new Process(['git', 'config', 'user.email', $this->webhooksAuth['email']]);
                $gitConfigProcess->run();

                $gitConfigProcess = new Process(['git', 'config',  'user.name', $this->webhooksAuth['name']]);
                $gitConfigProcess->run();

                //暂存服务器上的代码
                $process = new Process(['git', '--git-dir=/www/wwwroot/kerrycake_api/kerrycake_back/.git', '--work-tree=/www/wwwroot/kerrycake_api/kerrycake_back', 'stash']);
                $process->run();

                // 执行部署操作
                $process = new Process(['git', '--git-dir=/www/wwwroot/kerrycake_api/kerrycake_back/.git', '--work-tree=/www/wwwroot/kerrycake_api/kerrycake_back', 'pull', 'origin', 'dev']);
                $process->run();

                // 执行结果
                if (!$process->isSuccessful()) {
                   echo "Error: " . $process->getErrorOutput();die;
                }
                echo "Success: " . $process->getOutput();
            } else {
                // 测试 test_version
                echo "success";
            }
        }
    }
}
